package com.way;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author 魏彪
 */
public class WayLock {
    private static final Unsafe unsafe = getUnsafe();

    private volatile int state;

    private static long stateOffset;

    static {
        try {
            stateOffset = unsafe
                    .objectFieldOffset(WayLock
                            .class
                            .getDeclaredField("state"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public void lock() {
        while (!unsafe.compareAndSwapInt(this, stateOffset, 0, 1)) {
            System.out.println(stateOffset);
            System.out.println(Thread.currentThread().getName() + "正在加锁...");
        }
        System.out.println(Thread.currentThread().getName() + "加到锁了..");
    }

    public void unlock() {
        state = 0;
    }

    private static Unsafe getUnsafe() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
